<?php

require_once 'AjaxModule.php';
require_once 'models/Auth.php';
require_once 'models/User.php';

class UserModule extends AjaxModule {
	
	public function init() {
		parent::init ();
		LikeMVC_Session_Standard::getInstance ()->start ();
	}
	
	public function loginTask() {
		$uname = $this->getRequest ()->getParam ( 'username' );
		$passwd = $this->getRequest ()->getParam ( 'password' );
		if ($uname != null && $passwd != null) {
			$result = Models_Auth::AuthenticateUser ( $uname, $passwd );
			if ($result === true) {
				$this->view->setAjaxResponse ( array ('result' => 'success' ) );
				return;
			}
		}
		$this->view->setAjaxResponse ( array ('result' => 'failed' ) );
	}
	
	public function isLoginTask() {
		$result = Models_Auth::IsUserAuthenticated ();
		if ($result === true) {
			$this->view->setAjaxResponse ( array ('result' => 'true' ) );
			return;
		}
		$this->view->setAjaxResponse ( array ('result' => 'false' ) );
	}
	
	public function registerTask() {
		$errors = $this->isValid ();
		if (empty ( $errors )) {
			$uname = $this->getRequest ()->getParam ( 'username' );
			$passwd = $this->getRequest ()->getParam ( 'password' );
			$confirmedPasswd = $this->getRequest ()->getParam ( 'repassword' );
			$email = $this->getRequest ()->getParam ( 'email' );
			
			$user = new User(null);
			$user->username = $uname;
			$user->password = $passwd;
			$user->email = $email;
			$user->block = 0;
			$result = $user->insertRow();
			if ($result)	{
				$this->view->setAjaxResponse(array('result' => 'success'));
			} else {
				$this->view->setAjaxResponse(array('result' => 'failed', 'message' => 'Update failed'));
			}
			return;
		}
		$this->view->setAjaxResponse(array('result' => 'failed', 'message' => 'Errors caught', 'errors' => $errors));
	}
	
	public function isValid() {
		$errors = array ();
		$uname = $this->getRequest ()->getParam ( 'username' );
		$passwd = $this->getRequest ()->getParam ( 'password' );
		$confirmedPasswd = $this->getRequest ()->getParam ( 'repassword' );
		$email = $this->getRequest ()->getParam ( 'email' );
		
		if ($uname == null) {
			$errors [] = "Username undefined";
		}
		
		if ($passwd == null) {
			$errors [] = "Password undefined";
		}
		
		if ($confirmedPasswd == null) {
			$errors [] = "Confirmed password undefined";
		}
		
		if ($email == null) {
			$errors [] = "Email undefined";
		}
		
		if ($confirmedPasswd != $passwd) {
			$errors [] = "Password mismatch";
		}
		
		if (! User::IsUsernameValid ( $uname )) {
			$errors [] = "Username invalid";
		}
		
		if (! User::IsUsernameAvailable ( $uname )) {
			$errors [] = "Username not available";
		}
		
		if (! User::IsEmailAvailable ( $email )) {
			$errors [] = "Email not available";
		}
		
		return $errors;
	}
}

?>